import { Module } from 'vuex'
import { RootState } from '../types'
import { loginState } from './types'
import { accountLoginRequest, userInfoRequest, userMenusRequest } from '@/api/login/login'
import { LoginForm } from '@/views/login/components/types'
import { localCache, mapMenusToRoutes, mapMenusToPermissions } from '@/utils'

import router from '@/router'

// <S R> S模块中state的类型  R是根store中的state类型
const loginStore: Module<loginState, RootState> = {
  namespaced: true,
  state: () => ({
    userInfo: {},
    token: '',
    userMenus: [],
    path: '',
    permissions: []
  }),
  mutations: {
    SET_TOKE(state, token: string) {
      state.token = token
    },
    SET_USER_INFO(state, userInfo: any) {
      state.userInfo = userInfo
    },
    SET_USER_MENUS(state, userMenus: any) {
      // 登录过后拿到每个用户菜单
      state.userMenus = userMenus
      const routes = mapMenusToRoutes(userMenus)
      //将routes => router.main.children
      routes.forEach((route) => {
        router.addRoute('main', route)
      })

      // 获取用户按钮权限
      const permissions = mapMenusToPermissions(userMenus)
      state.permissions = permissions
    },
    CLEAR_USER_INFO(state) {
      state.token = ''
      state.userInfo = {}
      state.userMenus = []
    },
    SET_PATH(state, path) {
      state.path = path
    }
  },
  actions: {
    async getTokenAction({ commit, dispatch }, payload: LoginForm) {
      const loginResult = await accountLoginRequest({
        name: payload.userName || '',
        password: payload.passWord || ''
      })

      const { token, id } = loginResult.data
      commit('SET_TOKE', token)
      localCache.setCache('token', token)

      // 发送初始化请求
      dispatch('getInitialDataAction', null, { root: true })

      if (id) {
        const userInfoResult = await userInfoRequest(id)
        const userInfo = userInfoResult.data
        commit('SET_USER_INFO', userInfo)
        localCache.setCache('userInfo', userInfo)

        /*
          请求用户菜单
        */
        const userMenusResult = await userMenusRequest(userInfo.role.id)
        const userMenus = userMenusResult.data
        commit('SET_USER_MENUS', userMenus)
        localCache.setCache('userMenus', userMenus)
      }
      router.push('/main')
    },
    getPhoneTokenAction({ commit }, payload: any) {
      console.log(payload, '手机登录')
    },
    // 为了实现刷新不会丢失store的数据 刷新从本地读取菜单 用户信息等
    locadLocalLogin({ commit, dispatch }) {
      const token = localCache.getCache('token')
      if (token) {
        commit('SET_TOKE', token)

        // 调用根store的actions
        dispatch('getInitialDataAction', null, { root: true })
      }
      const userInfo = localCache.getCache('userInfo')
      if (userInfo) {
        commit('SET_USER_INFO', userInfo)
      }
      const userMenus = localCache.getCache('userMenus')
      if (userMenus) {
        commit('SET_USER_MENUS', userMenus)
      }
    },
    clearLocalLogin({ commit }) {
      localCache.deleteCache('userInfo')
      localCache.deleteCache('userMenus')
      commit('CLEAR_USER_INFO')
    }
  },
  getters: {}
}
export default loginStore
